package com.leetcode.offer.chapter3;

import com.leetcode.basic.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Dennis Li
 * @date 2020/7/13 8:48
 */
public class DeleteNode_18 {
    public ListNode deleteNode(ListNode head, ListNode node) {
        if (node == null || head == null) return head;
        if (node == head) {
            // 头结点
            ListNode temp = head.next;
            head.next = null;
            return temp;
        }
        // 知道节点的指针，可以直接复制节点，实现删除
        if (node.next != null) {
            ListNode temp = node.next;
            node.val = temp.val;
            node.next = temp.next;
        } else {
            // 删除尾结点.尾结点必须要知道前一个指针的坐标
            ListNode temp = head;
            while (temp.next != node) {
                temp = temp.next;
            }
            temp.next = null;
        }
        return head;
    }

    public ListNode deleteRepeateNode(ListNode head) {
        Set<Integer> set = new HashSet<>();
        ListNode cur = head;
        while (cur.next.next != null) {
            if (set.contains(cur.val)) {
                // 删除当前结点
                ListNode temp = cur.next;
                cur.val = temp.val;
                cur.next = temp.next;
            } else {
                set.add(cur.val);
                cur = cur.next;
            }
        }
        if(set.contains(cur.next.val))
            cur.next = null;
        return head;
    }
}
